import { prisma } from '../db'
import type { RechargeRecord } from '@prisma/client'
import { Decimal } from '@prisma/client/runtime/library'

export class RechargeService {
  /**
   * 创建充值记录
   */
  static async createRechargeRecord(data: {
    userId: number
    amount: number | string | Decimal
    status?: string
  }): Promise<RechargeRecord> {
    return await prisma.rechargeRecord.create({
      data: {
        userId: data.userId,
        amount: new Decimal(data.amount.toString()),
        status: data.status || 'pending'
      }
    })
  }

  /**
   * 根据 ID 获取充值记录
   */
  static async getRechargeRecordById(id: number): Promise<RechargeRecord | null> {
    return await prisma.rechargeRecord.findUnique({
      where: { id }
    })
  }

  /**
   * 获取用户的充值记录
   */
  static async getUserRechargeRecords(userId: number): Promise<RechargeRecord[]> {
    return await prisma.rechargeRecord.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' }
    })
  }

  /**
   * 更新充值记录状态
   */
  static async updateRechargeStatus(id: number, status: string): Promise<RechargeRecord> {
    return await prisma.rechargeRecord.update({
      where: { id },
      data: { status }
    })
  }

  /**
   * 获取所有充值记录
   */
  static async getAllRechargeRecords(): Promise<RechargeRecord[]> {
    return await prisma.rechargeRecord.findMany({
      orderBy: { createdAt: 'desc' }
    })
  }

  /**
   * 获取用户总充值金额
   */
  static async getUserTotalRecharge(userId: number): Promise<Decimal> {
    const result = await prisma.rechargeRecord.aggregate({
      where: {
        userId,
        status: 'completed'
      },
      _sum: {
        amount: true
      }
    })

    return result._sum.amount || new Decimal(0)
  }
}
